package cn.wolfcode.rbac.service.impl;

import cn.wolfcode.rbac.domain.Role;
import cn.wolfcode.rbac.ex.BusinessException;
import cn.wolfcode.rbac.mapper.RoleMapper;
import cn.wolfcode.rbac.query.QueryObject;
import cn.wolfcode.rbac.service.IRoleService;
import cn.wolfcode.rbac.web.vo.RoleVo;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

@Service
public class RoleServiceImpl  implements IRoleService {
    @Autowired
    private RoleMapper roleMapper;
    @Override
    public PageInfo query(QueryObject qo) {
        PageHelper.startPage(qo.getPageNum(),qo.getPageSize());
        return new PageInfo(roleMapper.selectAll());
    }

    @Override
    @Transactional
    public void add(RoleVo vo) {
        Role role = vo.getRole();
        if(role ==null){
            throw new BusinessException("非法操作");
        }
        roleMapper.insert(role);
        //维护中间表的关系
        List<Long> permissionIds = vo.getPermissionIds();
        if(permissionIds!=null && permissionIds.size()>=0){
            //尽量避免在循环中操作数据库，或者调用第三方接口
            roleMapper.insertPermissionRelationBatch(role.getId(),permissionIds);
        }
    }

    @Override
    public void update(Long id, RoleVo vo) {
        Role role = vo.getRole();
        if(id==null || role ==null){
            throw new BusinessException("非法操作");
        }
        role.setId(id);
        int count = roleMapper.updateByPrimaryKey(role);
        if(count==0){
            throw new BusinessException("更新失败");
        }
        //删除之前的关系
        roleMapper.deletePermissionRelationByRId(id);
        List<Long> permissionIds = vo.getPermissionIds();
        //插入新的关系
        if(permissionIds!=null && permissionIds.size()>0){
            roleMapper.insertPermissionRelationBatch(role.getId(),permissionIds);
        }
    }

    @Override
    public void delete(Long id) {
        int count = roleMapper.deleteByPrimaryKey(id);
        if(count==0){
            throw new BusinessException("删除失败");
        }
        //删除权限关系
        roleMapper.deletePermissionRelationByRId(id);
        //删除员工关系
        roleMapper.deleteEmployeeRelationByRId(id);
    }

    @Override
    public List<Role> listAll() {
        return roleMapper.selectAll();
    }

    @Override
    public List<Role> queryRoleByEId(Long id) {
        return roleMapper.queryRoleByEId(id);
    }

}
